package cn.kgc.fcm.dsbank.service.impl;


import cn.kgc.fcm.dsbank.dto.ResultDTO;
import cn.kgc.fcm.dsbank.entity.Employee;
import cn.kgc.fcm.dsbank.mapper.EmpMapper;
import cn.kgc.fcm.dsbank.mapper.EmpRoleMapper;
import cn.kgc.fcm.dsbank.service.EmpService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

@Service()
public class EmpServiceImpl implements EmpService {

    @Autowired
    private EmpMapper empMapper;

    @Autowired
    private EmpRoleMapper empRoleMapper;

    //BCrypt加密工具类对象
    @Autowired
    private BCryptPasswordEncoder bpe;

    private static final Logger log = LoggerFactory.getLogger(EmpServiceImpl.class);

    @Override
    public ResultDTO<List<Employee>> selectEmpAll() {

        List<Employee> employees = empMapper.selectEmpAll();
        if (CollectionUtils.isEmpty(employees)){
            return ResultDTO.buildError();
        }
        return ResultDTO.buildSuccess(employees);
    }

    @Override
    public ResultDTO<Employee> selectEmpById(Integer empId) {

        Employee employee = empMapper.selectEmpById(empId);


        return ResultDTO.buildSuccess(employee);
    }

    @Override
    public ResultDTO addEmp(Employee emp, Integer[] roleIds) {

        emp.setEmpPassword(bpe.encode(emp.getEmpPassword()));

        int i = empMapper.addEmp(emp);

        int j = 0;
        for (Integer roleId : roleIds) {
            j = empRoleMapper.addEmpRole(emp.getEmpId(), roleId);
        }
        if (i * j > 0){
            return ResultDTO.buildError();
        }

        return ResultDTO.buildSuccess();
    }


    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        Employee employee = empMapper.selectEmpByUsername(s);

        return employee;
    }
}
